(function(){
  'use strict';

  /**
   * Yihu前端组件命名空间声明 
   *
   * 启动angular有两种方法
   *    1.自动加载：html页面指令ng-app入口(一个页面只允许出现一个ng-app)
   *    2.手动加载：js中直接调用angular.bootstrap(element, [module]);
   *
   * angular.element(document).ready(function(){
   *   angular.bootstrap(angular.element(document), ['Yihu']);
   * })
   * 
   * Author: Alpha Tan 
   */
  var ssoTimerId;
  var Yihu = angular.module('Yihu', ['ui.bootstrap','ui.grid','ui.router','ngCookies','pascalprecht.translate', 'Yihu.ui','UserListModule','ArticleListModule','CategoryListModule','DerivativiesListModule','FilesListModule','CustomerListModule','ProductListModule','CommentListModule','ActivityListModule','ProductModelsListModule','OrderListModule', 'SeckillModule','CouponModule', 'GroupBuyModule', 'AuctionModule','FirstpayModule','SharepayModule','TuanModule', 'CmsTemplates','CmsServices', 'ncy-angular-breadcrumb','ngKeditor','oc.lazyLoad'])

  /**
   * 由于整个应用都会和路由打交道，所以这里把$state和$stateParams这两个对象放到$rootScope上，方便其它地方引用和注入。
   * 这里的run方法只会在angular启动的时候运行一次。
   *
   * 路由事件处理, 使用event.preventDefault()可以阻止模板解析的发生
    $stateChangeStart- 当模板开始解析之前触发
    $stateChangeSuccess- 当模板解析完成后触发
    $stateChangeError- 当模板解析过程中发生错误时触发
      $rootScope.$on('$stateChangeError', function(event, toState, toParams, fromState, fromParams, error){ ... })
    
    $viewContentLoading- 当视图开始加载，DOM渲染完成之前触发，该事件将在$scope链上广播此事件。
     $scope.$on('$viewContentLoading', function(event, viewConfig){ 
        // Access to all the view config properties.
        // and one special property 'targetView'
        // viewConfig.targetView 
      });
    $viewContentLoaded- 当视图加载完成，DOM渲染完成之后触发，视图所在的$scope发出该事件。
      $scope.$on('$viewContentLoaded', function(event){ ... })

   * @param  {[type]} $rootScope
   * @param  {[type]} $state
   * @param  {[type]} $stateParams
   * @return {[type]}
   */
  .run(['$rootScope', '$state', '$stateParams', '$log', '$http', '$location', '$window', 'Config', 'AUTH_EVENTS', 'AuthService', 'RichTextService', 'i18nService', '$interval', 'Session','$ocLazyLoad',
    function($rootScope, $state, $stateParams, $log, $http, $location, $window, Config, AUTH_EVENTS, AuthService, RichTextService, i18nService, $interval, Session, $ocLazyLoad) {
    $rootScope.$state = $state;
    $rootScope.$stateParams = $stateParams;
    $rootScope.$log = $log;
    $rootScope.$location = $location;
    $rootScope.$window = $window;

    $log.info('欢迎使用一虎一席组件库。');

    var psCtx = Config.profiles[Config.env].psContext;    
    var ctx = Config.profiles[Config.env].context;    
    $rootScope.defaultProfile = Config.userProfile.portrait;

    $rootScope.options = {
      uploadJson: psCtx+'/upload.do',
      fileManagerJson: ctx + '/editor/filemanager',
      articlesManagerJson: ctx + '/article/list',
      productsListJson: ctx + '/artwork/list',
      fileServerUrl: psCtx+'/download/',
      allowFileManager: true,
      width:'100%',
      height:'480px',
      items : [
        'source', '|', 'undo', 'redo', '|', 'preview', 'print', 'template', 'code', 'cut', 'copy', 'paste',
        'plainpaste', 'wordpaste', '|', 'justifyleft', 'justifycenter', 'justifyright',
        'justifyfull', 'insertorderedlist', 'insertunorderedlist', 'indent', 'outdent', 'subscript',
        'superscript', 'clearhtml', 'quickformat', 'selectall', '|', 'fullscreen', '/',
        'formatblock', 'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold',
        'italic', 'underline', 'strikethrough', 'lineheight', 'removeformat', '|', 'image', 'multiimage', 
        'table', 'splitter', 'emoticons', 'baidumap', 'pagebreak',
        'anchor', 'link', 'unlink'
      ],
      afterUpload: function (url, data, name) {  
        if(url && data.code===0){
          var form = {
            filetype: "image", 
            filename: data.fileName,
            fileid: data.id,
            filesize: data.fileSize
          };
          RichTextService.uploadCallback({}, form);
        }
      }
    };
    $rootScope.uploadUrl = psCtx+'/uploads.do';
    $rootScope.singleUploadUrl = psCtx+'/upload.do';
    $rootScope.downloadUrl = psCtx+'/download/';

    i18nService.setCurrentLang(Config.i18n || 'zh-cn');

    $ocLazyLoad.load(['libs/iCheck/skins/square/green.css', 'libs/iCheck/icheck.min.js']);

    //当前页面切换动画
    $rootScope.currentAnimated = true;

    //嵌套页切换动画
    $rootScope.nestedAnimated = false;

    $rootScope.discard = function(){
      $rootScope.currentAnimated = !$rootScope.currentAnimated;
      $state.go('^');
    };

    $rootScope.currentUser = Session.getUser();

    $rootScope.$on('$stateChangeStart', function(event, next, toParams, fromState, fromParams){ 
      if(next.name=='login'){
        return;// 如果是进入登录界面则允许
      }

      if(!AuthService.isAuthenticated()){
        event.preventDefault();
        $rootScope.$broadcast(AUTH_EVENTS.notAuthenticated, {from: next.name, params: toParams && toParams.id});
      }

      if(next.skipAuth){
        return;
      }

      if(!Config.enableAuth){
        return;
      }

      AuthService.isAuthorized(next, $rootScope.userPriviledges || [])
      .then(function(resoved){}, function(rejected){
        if(!rejected){
          event.preventDefault();
          if(AuthService.isAuthenticated()){
            //user is not allowed
            $rootScope.$broadcast(AUTH_EVENTS.notAuthorized);
          }else{
            //user is not logged in            
            $rootScope.$broadcast(AUTH_EVENTS.notAuthenticated, {from: next.name, params: toParams && toParams.id});
          }
        }
      });
      
      // var authorizedRoles = next.data.authorizedRoles || [];
      // if(authorizedRoles.length && !AuthService.isAuthorized(authorizedRoles)){
      //   event.preventDefault();
      //   if(AuthService.isAuthenticated()){
      //     //user is not allowed
      //     $rootScope.$broadcast(AUTH_EVENTS.notAuthorized);
      //   }else{
      //     //user is not logged in            
      //     $rootScope.$broadcast(AUTH_EVENTS.notAuthenticated, {from: next.name, params: toParams && toParams.id});
      //   }
      // }
    });

    $rootScope.$on(AUTH_EVENTS.notAuthenticated, function(event, args){
      $state.go('login', {from: args && args.from, params: args && args.params});
    });

    $rootScope.$on(AUTH_EVENTS.loginSuccess, function(event, args){
      if(!ssoTimerId){
        ssoTimerId = $interval(refreshSSO, Config.ssoInterval);
      }

      if(args && args.from){
        if(args.params){
          $state.go(args.from, {id:args.params});
        }else{
          $state.go(args.from);
        }
      }else{
        $state.go('index');
      }
    });

    $rootScope.$on(AUTH_EVENTS.routerFailed, function(event, args){
      $state.go('index');
    });

    $rootScope.$on(AUTH_EVENTS.sessionTimeout, function(event, args){
      if(ssoTimerId){
        $interval.cancel(ssoTimerId);
      }
      $state.go('login', {from: args && args.from, params: args && args.params});
    });

    $rootScope.$on(AUTH_EVENTS.notAuthorized, function(event, args){
      $state.go('401');
    });

    $rootScope.$on(AUTH_EVENTS.pageNotFound, function(event, args){
      $state.go('404');
    });

    $rootScope.$on(AUTH_EVENTS.internalError, function(event, args){
      $state.go('500');
    });
  }])

  /**
   * Yihu前端路由配置，采用angular-ui-router替换
   */
  .config(function($stateProvider, $urlRouterProvider, $breadcrumbProvider, USER_ROLES, $httpProvider){
    $httpProvider.interceptors.push(['$injector', function ($injector) {
      return $injector.get('AuthInterceptor');
    }]);

    $breadcrumbProvider.setOptions({
      prefixStateName: 'index'
    });

    $urlRouterProvider.otherwise('/index');

    $stateProvider.state('index', {
      url:'/index',
      templateUrl:'tpls/main.html',
      data:{
        authorizedRoles:[USER_ROLES.admin, USER_ROLES.normal]
      },
      ncyBreadcrumb: {
        label: 'Home',
        icon: 'fa fa-home'
      }
    })
    .state('login', {
      url:'/signIn?from&params',
      templateUrl:'tpls/user/login.html',
      controller:'UserLoginCtrl',
      ncyBreadcrumb: {
        label: '用户登录'
      },
      skipAuth: true
    })
    .state('401', {
      url:'/401',
      templateUrl:'tpls/common/401.html',
      ncyBreadcrumb: {
        label: '没有权限'
      },
      skipAuth: true
    })
    .state('404', {
      url:'/404',
      templateUrl:'tpls/common/404.html',
      ncyBreadcrumb: {
        label: '找不到当前页'
      },
      skipAuth: true
    })
    .state('500', {
      url:'/500',
      templateUrl:'tpls/common/500.html',
      ncyBreadcrumb: {
        label: '错误页'
      },
      skipAuth: true
    })
    .state('999', {
      url:'/999',
      templateUrl:'tpls/common/999.html',
      ncyBreadcrumb: {
        label: '建设中'
      },
      skipAuth: true
    })
    .state('message', {
      url:'/message',
      templateUrl:'tpls/user/message.html',
      ncyBreadcrumb: {
        label: '我的消息'
      },
      controller: 'MessageCtrl'
    })
    .state('follow', {
      url:'/follow',
      templateUrl:'tpls/user/follow.html',
      ncyBreadcrumb: {
        label: '我的关注'
      }
    })
    .state('stats', {
      url:'/stats',
      templateUrl:'tpls/user/stats.html',
      ncyBreadcrumb: {
        label: '用户统计'
      }
    })
    .state('setting', {
      url:'/setting',
      templateUrl:'tpls/user/setting.html',
      ncyBreadcrumb: {
        label: '系统设置'
      }
    })
    .state('user', {
      url:'/user?reset',
      templateUrl:'tpls/user/userGrid.html',
      controller:'UserListCtrl',
      data:{
        authorizedRoles:[USER_ROLES.admin, USER_ROLES.normal]
      },
      ncyBreadcrumb: {
        label: '用户管理'
      },
    })
    .state('userview', {
      url:'/userview?reset',
      templateUrl:'tpls/user/userView.html',
      controller:'UserListViewCtrl',
      data:{
        authorizedRoles:[USER_ROLES.admin, USER_ROLES.normal]
      },
      ncyBreadcrumb: {
        label: '用户管理'
      },
    })
    .state('user.addUser', {
      url:'/add',
      views:{
        '@':{
          templateUrl:'tpls/user/add.html',
          controller:'AddUserCtrl'
        }
      },
      ncyBreadcrumb: {
        label: '新增用户',
        parent: 'user'
      }
    })
    .state('user.editUser', {
      url:'/edit/:id',
      views:{
        '@':{
          templateUrl:'tpls/user/edit.html',
          controller:'EditUserCtrl'
        }
      },
      ncyBreadcrumb: {
        label: '更新用户',
        parent: 'user'
      },
      resolve:{
        User: function($q, $stateParams, UserService){
          return UserService.findOne({id: $stateParams.id}).$promise;
        }
      }
    })
    .state('user.changePwd', {
      url:'/changePwd',
      views:{
        '@':{
          templateUrl:'tpls/user/changePwd.html',
          controller:'ChangePwdCtrl'
        }
      },
      ncyBreadcrumb: {
        label: '修改密码',
        parent: 'user'
      }
    })
    .state('user.updateLevel', {
      url:'/level/:id/update',
      views:{
        '@':{
          templateUrl:'tpls/user/updateLevel.html',
          controller:'UpdateLevelCtrl'
        }
      },
      ncyBreadcrumb: {
        label: '设置级别',
        parent: 'user'
      },
      resolve:{
        User: function($stateParams, UserService){
          return UserService.findOne({id: $stateParams.id}).$promise;
        }
      }
    })
    .state('user.updateAgentLevel', {
      url:'/agentlevel/:id/update',
      views:{
        '@':{
          templateUrl:'tpls/user/updateLevel.html',
          controller:'UpdateLevelCtrl'
        }
      },
      ncyBreadcrumb: {
        label: '设置级别',
        parent: 'user'
      },
      resolve:{
        User: function($stateParams, UserService){
          return UserService.findOne({id: $stateParams.id}).$promise;
        }
      }
    })
    .state('user.updateRelation', {
      url:'/:id/relation',
      views:{
        '@':{
          templateUrl:'tpls/user/updateRelation.html',
          controller:'UpdateRelationCtrl'
        }
      },
      ncyBreadcrumb: {
        label: '设置推荐人',
        parent: 'user'
      },
      resolve:{
        User: function($stateParams, UserService){
          return UserService.findOne({id: $stateParams.id}).$promise;
        }
      }
    })
    .state('user.view', {
      url:'/:id/view',
      views:{
        '@':{
          templateUrl:'tpls/user/view.html',
          controller:'ViewUserCtrl'
        }
      },
      ncyBreadcrumb: {
        label: '用户详情',
        parent: 'user'
      },
      resolve:{
        User: function($q, $stateParams, UserService){
          return UserService.findOne({id: $stateParams.id}).$promise;
        }
      }
    })
    .state('usergroup', {
      url:'/user/group',
      templateUrl:'tpls/userGroup/grid.html',
      controller:'UserGroupListCtrl',
      data:{
        authorizedRoles:[USER_ROLES.admin, USER_ROLES.normal]
      },
      ncyBreadcrumb: {
        label: '用户组管理'
      }
    })
    .state('usergroup.add', {
      url:'/add',
      views:{
        '@':{
          templateUrl:'tpls/userGroup/add.html',
          controller:'AddUserGroupCtrl'
        }
      },
      ncyBreadcrumb: {
        label: '新增用户组',
        parent: 'usergroup'
      }
    })
    .state('usergroup.edit', {
      url:'/edit/:id',
      views:{
        '@':{
          templateUrl:'tpls/userGroup/edit.html',
          controller:'EditUserGroupCtrl'
        }
      },
      ncyBreadcrumb: {
        label: '更新用户组',
        parent: 'usergroup'
      },
      resolve:{
        UserGroup: function($q, $stateParams, UserGroupService){
          return UserGroupService.findOne({id: $stateParams.id}).$promise;
        }
      }
    })
    .state('usergroup.assign', {
      url:'/assign/:id',
      views:{
        '@':{
          templateUrl:'tpls/userGroup/assign.html',
          controller:'AssignUserGroupCtrl'
        }
      },
      ncyBreadcrumb: {
        label: '用户组指派用户',
        parent: 'usergroup'
      },
      resolve:{
        UserGroup: function($stateParams, UserGroupService){
          return UserGroupService.getUsers({groupId: $stateParams.id}).$promise;
        }
      }
    })
    .state('userrole', {
      url:'/user/role',
      templateUrl:'tpls/userRole/grid.html',
      controller:'UserRoleListCtrl',
      data:{
        authorizedRoles:[USER_ROLES.admin, USER_ROLES.normal]
      },
      ncyBreadcrumb: {
        label: '角色管理'
      }
    })
    .state('userrole.add', {
      url:'/add',
      views:{
        '@':{
          templateUrl:'tpls/userRole/add.html',
          controller:'AddUserRoleCtrl'
        }
      },
      ncyBreadcrumb: {
        label: '新增角色',
        parent: 'userrole'
      }
    })
    .state('userrole.edit', {
      url:'/edit/:id',
      views:{
        '@':{
          templateUrl:'tpls/userRole/edit.html',
          controller:'EditUserRoleCtrl'
        }
      },
      ncyBreadcrumb: {
        label: '更新角色',
        parent: 'userrole'
      },
      resolve:{
        UserRole: function($stateParams, UserRoleService){
          return UserRoleService.findOne({id: $stateParams.id}).$promise;
        }
      }
    })
    .state('userrole.assign', {
      url:'/assign/:id',
      views:{
        '@':{
          templateUrl:'tpls/userRole/assign.html',
          controller:'AssignUserRoleCtrl'
        }
      },
      ncyBreadcrumb: {
        label: '分配用户组',
        parent: 'userrole'
      },
      resolve:{
        UserRole: function($stateParams, UserRoleService){
          return UserRoleService.getRoleGroups({roleId: $stateParams.id}).$promise;
        }
      }
    })
    .state('userrole.grant', {
      url:'/grant/:id',
      views:{
        '@':{
          templateUrl:'tpls/userRole/grant.html',
          controller:'GrantUserRoleCtrl'
        }
      },
      ncyBreadcrumb: {
        label: '角色授权',
        parent: 'userrole'
      },
      resolve:{
        UserRole: function($stateParams, UserRoleService){
          return UserRoleService.getRoleGroups({roleId: $stateParams.id}).$promise;
        }
      }
    }) 
    .state('permissions', {
      url:'/user/permissions/:id',
      templateUrl:'tpls/permits/grid.html',
      controller:'PermissionListCtrl',
      data:{
        authorizedRoles:[USER_ROLES.admin, USER_ROLES.normal]
      },
      ncyBreadcrumb: {
        label: '权限管理'
      }

    })
    .state('permissions.add', {
      url:'/add',
      views:{
        '@':{
          templateUrl:'tpls/permits/add.html',
          controller:'AddPermissionCtrl'
        }
      },
      ncyBreadcrumb: {
        label: '新增权限',
        parent: 'permissions'
      }
    })
    .state('permissions.edit', {
      url:'/edit/:permitId',
      views:{
        '@':{
          templateUrl:'tpls/permits/edit.html',
          controller:'EditPermissionCtrl'
        }
      },
      ncyBreadcrumb: {
        label: '更新权限',
        parent: 'permissions'
      },
      resolve: {
        Priviledge: function($stateParams, PermissionService){
          return PermissionService.findOne({id: $stateParams.permitId}).$promise;
        }
      }
    })
    .state('permissions.children', {
      url:'/children/:permitId',
      views:{
        '@':{
          templateUrl:'tpls/permits/addChild.html',
          controller:'AddChildPermissionCtrl'
        }
      },
      ncyBreadcrumb: {
        label: '增加子级权限',
        parent: 'permissions'
      },
      resolve: {
        Priviledge: function($stateParams, PermissionService){
          return PermissionService.findOne({id: $stateParams.permitId}).$promise;
        }
      }
    })
    .state('resources', {
      url:'/user/resources/:id',
      templateUrl:'tpls/resource/grid.html',
      controller:'ResourcesListCtrl',
      data:{
        authorizedRoles:[USER_ROLES.admin, USER_ROLES.normal]
      },
      ncyBreadcrumb: {
        label: '资源管理',
        parent: 'permissions'
      }
    })
    .state('resources.add', {
      url:'/add',
      views:{
        '@':{
          templateUrl:'tpls/resource/add.html',
          controller:'AddResourceCtrl'
        }
      },
      ncyBreadcrumb: {
        label: '新增资源',
        parent: 'resources'
      }
    })
    .state('resources.edit', {
      url:'/edit/:id',
      views:{
        '@':{
          templateUrl:'tpls/resource/edit.html',
          controller:'EditResourceCtrl'
        }
      },
      ncyBreadcrumb: {
        label: '更新资源',
        parent: 'resources'
      },
      resolve:{
        Resource: function($stateParams, ResoucesService){
          return ResoucesService.findOne({id: $stateParams.id}).$promise;
        }
      }
    })
    .state('datadict', {
      url:'/datadict/:id',
      templateUrl:'tpls/dataDict/grid.html',
      controller:'DataDictListCtrl',
      data:{
        authorizedRoles:[USER_ROLES.admin, USER_ROLES.normal]
      },
      ncyBreadcrumb: {
        label: '数据字典管理'
      }
    })
    .state('datadict.add', {
      url:'/add',
      views:{
        '@':{
          templateUrl:'tpls/dataDict/add.html',
          controller:'AddDataDictCtrl'
        }
      },
      ncyBreadcrumb: {
        label: '新增数据字典',
        parent: 'datadict'
      }
    })
    .state('datadict.edit', {
      url:'/edit/:id',
      views:{
        '@':{
          templateUrl:'tpls/dataDict/edit.html',
          controller:'EditDataDictCtrl'
        }
      },
      ncyBreadcrumb: {
        label: '更新数据字典',
        parent: 'datadict'
      },
      resolve:{
        DataDict: function($stateParams, DataDictService){
          return DataDictService.findOne({id: $stateParams.id}).$promise;
        }
      }
    })
    .state('datadict.children', {
      url:'/children/:dictId',
      views:{
        '@':{
          templateUrl:'tpls/dataDict/addChild.html',
          controller:'AddDataDictChildCtrl'
        }
      },
      ncyBreadcrumb: {
        label: '增加子级配置项',
        parent: 'datadict'
      },
      resolve:{
        DataDict: function($stateParams, DataDictService){
          return DataDictService.findOne({id: $stateParams.dictId}).$promise;
        }
      }
    })
    .state('tag', {
      url:'/tag',
      views:{
        '@':{
          templateUrl:'tpls/tag/grid.html',
          controller:'TagListCtrl'
        }
      },
      data:{
        authorizedRoles:[USER_ROLES.admin, USER_ROLES.normal]
      },
      ncyBreadcrumb: {
        label: '标签管理'
      }
    })
    .state('tag.add', {
      url:'/add',
      views:{
        '@':{
          templateUrl:'tpls/tag/add.html',
          controller:'AddTagCtrl'
        }
      },
      ncyBreadcrumb: {
        label: '新增标签',
        parent: 'tag'
      }
    })
    .state('tag.edit', {
      url:'/edit/:id',
      views:{
        '@':{
          templateUrl:'tpls/tag/edit.html',
          controller:'EditTagCtrl'
        }
      },
      ncyBreadcrumb: {
        label: '更新标签',
        parent: 'tag'
      },
      resolve:{
        Tag: function(TagService, $stateParams){
          return TagService.findOne({id: $stateParams.id}).$promise;
        }
      }
    })
    .state('poster', {
      url:'/poster',
      views:{
        '@':{
          templateUrl:'tpls/navbar/grid.html',
          controller:'PosterListCtrl'
        }
      },
      data:{
        authorizedRoles:[USER_ROLES.admin, USER_ROLES.normal]
      },
      ncyBreadcrumb: {
        label: '轮播广告管理'
      }
    })
    .state('poster.add', {
      url:'/add',
      views:{
        '@':{
          templateUrl:'tpls/navbar/add.html',
          controller:'AddPosterCtrl'
        }
      },
      ncyBreadcrumb: {
        label: '新增轮播广告',
        parent: 'poster'
      }
    })
    .state('poster.edit', {
      url:'/edit/:id',
      views:{
        '@':{
          templateUrl:'tpls/navbar/edit.html',
          controller:'EditPosterCtrl'
        }
      },
      ncyBreadcrumb: {
        label: '更新轮播广告',
        parent: 'poster'
      },
      resolve:{
        Poster: function(PosterService, $stateParams){
          return PosterService.findOne({id: $stateParams.id}).$promise;
        }
      }
    })
    .state('article', {
      url:'/article',
      templateUrl:'tpls/article/grid.html',
      controller:'ArticleListCtrl',
      data:{
        authorizedRoles:[USER_ROLES.admin, USER_ROLES.normal]
      },
      ncyBreadcrumb: {
        label: '文章管理'
      }, 
      resolve:{
        Categories: function(CategoryService){
          return CategoryService.getList({}, {currentPage:1,pageSize:10000}).$promise;
        }
      }
    })
    .state('myarticle', {
      url:'/myarticle',
      templateUrl:'tpls/article/my.html',
      controller:'MyArticleListCtrl',
      data:{
        authorizedRoles:[USER_ROLES.admin, USER_ROLES.normal]
      },
      ncyBreadcrumb: {
        label: '文章管理'
      }, 
      resolve:{
        Categories: function(CategoryService){
          return CategoryService.getList({}, {currentPage:1,pageSize:10000}).$promise;
        }
      }
    })
    .state('faq', {
      url:'/faq',
      templateUrl:'tpls/article/faq.html',
      controller:'FaqArticleListCtrl',
      data:{
        authorizedRoles:[USER_ROLES.admin, USER_ROLES.normal]
      },
      ncyBreadcrumb: {
        label: '文章管理'
      }, 
      resolve:{
        Categories: function(CategoryService){
          return CategoryService.getList({}, {currentPage:1,pageSize:10000}).$promise;
        }
      }
    })
    .state('article.addArticle', {
      url:'/add',
      views: {
        "@" : {
          templateUrl:'tpls/article/add.html',
          controller:'AddArticleCtrl'
        }
      },
      ncyBreadcrumb: {
        label: '新增文章',
        parent: 'article'
      }, 
      resolve:{
        Categories: function(CategoryService){
          return CategoryService.getList({}, {currentPage:1,pageSize:10000}).$promise;
        },
        Unsaved: function(Store, BasicService){
          var unsaved = {};
          unsaved.id = Store.getUnsaved('article');

          BasicService.getUnsaved({}, { autoKey: unsaved.id }, function(data){
            unsaved.content = data.content;
          });
          return unsaved;
        }
      }
    })
    .state('article.editArticle', {
      url:'/edit/{id:.*}?:type',
      views: {
        "@" : {
          templateUrl:'tpls/article/edit.html',
          controller:'EditArticleCtrl'
        }
      },
      ncyBreadcrumb: {
        label: '更新文章',
        parent: 'article'
      },
      resolve:{
        Unsaved: function($stateParams, Store, BasicService){
          var unsaved = {};
          unsaved.id = Store.getUnsaved('article', $stateParams.id);

          BasicService.getUnsaved({}, { autoKey: unsaved.id }, function(data){
            unsaved.content = data.content;
          });
          return unsaved;
        }, 
        Categories: function($q, $stateParams, CategoryService, ArticleService){
          var article = {};

          $q.all([
            CategoryService.getList({}, {currentPage:1,pageSize:10000}).$promise,
            ArticleService.findOne({id: $stateParams.id}).$promise
          ]).then(function(results){
            article.categoryList = results[0].categories;
            var articleObj = results[1];
            angular.extend(article, articleObj);
          });
          return article;
        }
      }
    })
    .state('article.viewArticle', {
      url:'/view/:id',
      views: {
        "@" : {
          templateUrl:'tpls/article/view.html',
          controller:'ViewArticleCtrl'
        }
      },
      ncyBreadcrumb: {
        label: '查看文章',
        parent: 'article'
      }, 
      resolve:{
        Article: function($stateParams, ArticleService){
          return ArticleService.findOne({id: $stateParams.id}).$promise;
        }
      }
    })
    .state('article.categories', {
      url:'/category',
      views:{
        "@":{
          templateUrl:'tpls/category/grid.html',
          controller:'CategoryListCtrl',
        }
      },
      ncyBreadcrumb: {
        label: '文章类别管理',
        parent:'article'
      }
    })
    .state('article.categories.addCategory', {
      url:'/add',
      views: {
        "@" : {
          templateUrl:'tpls/category/add.html',
          controller:'AddCategoryCtrl'
        }
      },
      ncyBreadcrumb: {
        label: '新增文章类别',
        parent: 'article.categories'
      }
    })
    .state('article.categories.editCategory', {
      url:'/edit/:id',
      views: {
        "@" : {
          templateUrl:'tpls/category/edit.html',
          controller:'EditCategoryCtrl'
        }
      },
      ncyBreadcrumb: {
        label: '更新文章类别',
        parent: 'article.categories'
      },
      resolve:{
        Categories: function($q, $stateParams, CategoryService){
          var category = {};

          $q.all([
            CategoryService.getList({}, {currentPage:1,pageSize:10000}).$promise,
            CategoryService.findOne({id: $stateParams.id}).$promise
          ]).then(function(results){
            category.categoryList = results[0].categories;
            var categoryObj = results[1];
            angular.extend(category, categoryObj);
          });
          return category;
        }
      }
    })
    .state('files', {
      url:'/files',
      templateUrl:'tpls/files/grid.html',
      controller:'FilesListCtrl',
      data:{
        authorizedRoles:[USER_ROLES.admin, USER_ROLES.normal]
      },
      ncyBreadcrumb: {
        label: '图片管理'
      }
    })
    .state('automachine', {
      url:'/automachine',
      templateUrl:'tpls/automachine.html',
      data:{
        authorizedRoles:[USER_ROLES.admin, USER_ROLES.normal]
      },
      ncyBreadcrumb: {
        label: '售卖机管理'
      }
    })
    .state('customers', {
      url:'/customers',
      templateUrl:'tpls/customer/main.html',
      controller:'CustomerListCtrl',
      data:{
        authorizedRoles:[USER_ROLES.admin, USER_ROLES.normal]
      },
      ncyBreadcrumb: {
        label: '客户管理'
      }
    })
    .state('comment', {
      url:'/comment',
      templateUrl:'tpls/comments/grid.html',
      controller:'CommentListCtrl',
      data:{
        authorizedRoles:[USER_ROLES.admin, USER_ROLES.normal]
      },
      ncyBreadcrumb: {
        label: '评论管理'
      }
    })
    .state('products', {
      url:'/products?:type&:reset',
      templateUrl:'tpls/product/grid.html',
      controller:'ProductListCtrl',
      data:{
        authorizedRoles:[USER_ROLES.admin, USER_ROLES.normal]
      },
      ncyBreadcrumb: {
        label: '商品管理'
      },
      resolve:{
        Artwork:function($q, BasicService){
          var artwork = {};

          $q.all([
            BasicService.getArtworkType({}).$promise,
            BasicService.getCommodityStates({}).$promise
          ]).then(function(results){
            artwork.typeList = results[0].childrens;
            artwork.commodityStatesList = results[1].info;
          });
          return artwork; 
        }
      }
    })
    .state('products.addProduct', {
      url:'/add',
      views: {
        "@" : {
          templateUrl:'tpls/product/add.html',
          controller:'AddProductCtrl'
        }
      },
      ncyBreadcrumb: {
        label: '新增商品',
        parent: 'products'
      },
      resolve:{
        Unsaved: function(Store, BasicService){
          var unsaved = {};
          unsaved.id = Store.getUnsaved('artwork');

          BasicService.getUnsaved({}, { autoKey: unsaved.id }, function(data){
            unsaved.content = data.content;
          });
          return unsaved;
        }, 
        Artwork:function($q, BasicService){
          var artwork = {unit:'cm'};

          $q.all([
            BasicService.getArtworkType({}).$promise,
            BasicService.getCommodityStates({}).$promise
          ]).then(function(results){
            artwork.typeList = results[0].childrens;
            artwork.commodityStatesList = results[1].info;
          });
          return artwork; 
        }
      }
    })
    .state('products.editProduct', {
      url:'/edit/:id',
      views: {
        "@" : {
          templateUrl:'tpls/product/edit.html',
          controller:'EditProductCtrl',
        }
      },
      ncyBreadcrumb: {
        label: '更新商品',
        parent: 'products'
      },
      resolve:{
        Unsaved: function($stateParams, Store, BasicService){
          var unsaved = {};
          unsaved.id = Store.getUnsaved('artwork', $stateParams.id);

          BasicService.getUnsaved({}, { autoKey: unsaved.id }, function(data){
            unsaved.content = data.content;
          });
          return unsaved;
        }, 
        Artwork:function($q, $stateParams, BasicService,ArtworkService){
          var artwork = {};

          $q.all([
            BasicService.getArtworkType({}).$promise,
            BasicService.getCommodityStates({}).$promise, 
            ArtworkService.findOne({id:$stateParams.id}).$promise
          ]).then(function(results){
            artwork.typeList = results[0].childrens;
            artwork.commodityStatesList = results[1].info;

            var artworkObj = results[2];
            angular.extend(artwork, artworkObj);
            artwork.status = artworkObj.commodityStates.id;
          });
          return artwork; 
        }
      }
    })
    .state('products.comments', {
      url:'/:id/comments',
      views: {
        "@" : {
          templateUrl:'tpls/product/comments.html',
          controller:'ProductCommentsCtrl'
        }
      },
      ncyBreadcrumb: {
        label: '商品评论管理',
        parent: 'products'
      }
    })
    .state('products.comments.add', {
      url:'/add',
      views: {
        "@" : {
          templateUrl:'tpls/comments/add.html',
          controller:'AddCommentCtrl'
        }
      },
      ncyBreadcrumb: {
        label: '新增评论',
        parent: 'products.comments'
      }
    })
    .state('products.comments.reply', {
      url:'/:cid',
      views: {
        "@" : {
          templateUrl:'tpls/comments/replygrid.html',
          controller:'CommentReplyListCtrl'
        }
      },
      ncyBreadcrumb: {
        label: '查看评论回复',
        parent: 'products.comments'
      }
    })
    .state('products.comments.reply.add', {
      url:'/reply',
      views: {
        "@" : {
          templateUrl:'tpls/comments/addreply.html',
          controller:'AddCommentReplyCtrl'
        }
      },
      ncyBreadcrumb: {
        label: '新增评论回复',
        parent: 'products.comments.reply'
      },
      resolve:{
        Comment:function($stateParams, CommentService){
          return CommentService.findOne({id:$stateParams.cid}).$promise;
        }
      }
    })
    .state('products.comments.edit', {
      url:'/edit/:cid',
      views: {
        "@" : {
          templateUrl:'tpls/comments/edit.html',
          controller:'EditCommentCtrl'
        }
      },
      ncyBreadcrumb: {
        label: '修改评论',
        parent: 'products.comments'
      },
      resolve:{
        Comment:function($stateParams, CommentService){
          return CommentService.findOne({id:$stateParams.cid}).$promise;
        }
      }
    })
    .state('products.derivatives', {
      url:'/derivatives',
      views:{
        "@":{
          templateUrl:'tpls/derivatives/grid.html',
          controller:'DerivativiesListCtrl',
        }
      },
      ncyBreadcrumb: {
        label: '衍生品管理',
        parent:'products'
      },
      resolve:{
        Derivativies:function($q, BasicService){
          var derivativies = {};

          $q.all([
            BasicService.getDerivativesCategories({}).$promise, 
            BasicService.getCommodityStates({}).$promise,
            BasicService.getArtworkType({}).$promise
          ]).then(function(results){
            derivativies.categoryList = results[0].info;
            derivativies.commodityStatesList = results[1].info;
            derivativies.typeList = results[2].info;
          });
          return derivativies; 
        }
      }
    })
    .state('products.derivatives.addDerivativies', {
      url:'/add',
      views: {
        "@" : {
          templateUrl:'tpls/derivatives/add.html',
          controller:'AddDerivativiesCtrl'
        }
      },
      ncyBreadcrumb: {
        label: '新增衍生品',
        parent: 'products.derivatives'
      },
      resolve:{
        Unsaved: function(Store, BasicService){
          var unsaved = {};
          unsaved.id = Store.getUnsaved('derivative');

          BasicService.getUnsaved({}, { autoKey: unsaved.id }, function(data){
            unsaved.content = data.content;
          });
          return unsaved;
        }, 
        Derivativies:function($q, BasicService){
          var derivativies = {};

          $q.all([
            BasicService.getDerivativesCategories({}).$promise, 
            BasicService.getCommodityStates({}).$promise,
            BasicService.getArtworkAuthor({}).$promise,
            BasicService.getMaterialList({}).$promise,
            BasicService.getArtworkType({}).$promise
          ]).then(function(results){
            derivativies.categoryList = results[0].info;
            derivativies.commodityStatesList = results[1].info;
            derivativies.artistList = results[2].info;
            derivativies.materialList = results[3].info;
            derivativies.typeList = results[4].info;
          });
          return derivativies; 
        }
      }
    })
    .state('products.derivatives.editDerivativies', {
      url:'/edit/:id',
      views: {
        "@" : {
          templateUrl:'tpls/derivatives/edit.html',
          controller:'EditDerivativiesCtrl'
        }
      },
      ncyBreadcrumb: {
        label: '更新衍生品',
        parent: 'products.derivatives'
      },
      resolve:{
        Unsaved: function($stateParams, Store, BasicService){
          var unsaved = {};
          unsaved.id = Store.getUnsaved('derivative', $stateParams.id);

          BasicService.getUnsaved({}, { autoKey: unsaved.id }, function(data){
            unsaved.content = data.content;
          });
          return unsaved;
        }, 
        Derivativies:function($q, $stateParams, BasicService, DerivativiesService){
          var derivativies = {};

          $q.all([
            BasicService.getDerivativesCategories({}).$promise, 
            BasicService.getCommodityStates({}).$promise,
            BasicService.getArtworkAuthor({}).$promise,
            BasicService.getMaterialList({}).$promise,
            DerivativiesService.findOne({id:$stateParams.id}).$promise,
            BasicService.getArtworkType({}).$promise
          ]).then(function(results){
            derivativies.categoryList = results[0].info;
            derivativies.commodityStatesList = results[1].info;
            derivativies.artistList = results[2].info;
            derivativies.materialList = results[3].info;
            derivativies.typeList = results[5].info;

            var derivativiesObj = results[4];
            angular.extend(derivativies, derivativiesObj);
          });
          return derivativies; 
        }
      }
    })
    .state('products.models', {
      url:'/models/:id',
      views:{
        "@":{
          templateUrl:'tpls/productModels/grid.html',
          controller:'ProductModelsListCtrl',
        }
      },
      ncyBreadcrumb: {
        label: '产品款式管理',
        parent:'products'
      }
    })
    .state('products.models.add', {
      url:'/add',
      views: {
        "@" : {
          templateUrl:'tpls/productModels/add.html',
          controller:'AddProductModelsCtrl'
        }
      },
      ncyBreadcrumb: {
        label: '新增产品款式',
        parent: 'products.models'
      },
      resolve:{
        Pid:function($stateParams){
          return $stateParams.id;
        }
      }
    })
    .state('products.models.edit', {
      url:'/edit/:mid',
      views: {
        "@" : {
          templateUrl:'tpls/productModels/edit.html',
          controller:'EditProductModelsCtrl'
        }
      },
      ncyBreadcrumb: {
        label: '更新产品款式',
        parent: 'products.models'
      },
      resolve:{
        Models:function($q, $stateParams, ProductModelsService){
          return ProductModelsService.findOne({id:$stateParams.mid}).$promise;
        }
      }
    })    
    .state('activity', {
      url:'/activity',
      templateUrl:'tpls/activity/grid.html',
      controller:'ActivityListCtrl',
      data:{
        authorizedRoles:[USER_ROLES.admin, USER_ROLES.normal]
      },
      ncyBreadcrumb: {
        label: '主题活动管理'
      }
    })
    .state('activity.add', {
      url:'/add',
      views:{
        '@':{
          templateUrl:'tpls/activity/add.html',
          controller:'AddActivityCtrl'
        }
      },
      ncyBreadcrumb: {
        label: '新增主题活动',
        parent: 'activity'
      },
      resolve:{
        Unsaved: function(Store, BasicService){
          var unsaved = {};
          unsaved.id = Store.getUnsaved('activity');

          BasicService.getUnsaved({}, { autoKey: unsaved.id }, function(data){
            unsaved.content = data.content;
          });
          return unsaved;
        }
      }
    })
    .state('activity.edit', {
      url:'/edit/:id',
      views:{
        '@':{
          templateUrl:'tpls/activity/edit.html',
          controller:'EditActivityCtrl'
        }
      },
      ncyBreadcrumb: {
        label: '更新主题活动',
        parent: 'activity'
      },
      resolve: {
        Unsaved: function($stateParams, Store, BasicService){
          var unsaved = {};
          unsaved.id = Store.getUnsaved('activity', $stateParams.id);

          BasicService.getUnsaved({}, { autoKey: unsaved.id }, function(data){
            unsaved.content = data.content;
          });
          return unsaved;
        }, 
        Activity: function($stateParams, ActivityService){
          return ActivityService.findOne({id: $stateParams.id}).$promise;
        }
      }
    }) 
    .state('orders', {
      url:'/orders?:status&:reset',
      templateUrl:'tpls/order/grid.html',
      controller:'OrderListCtrl',
      data:{
        authorizedRoles:[USER_ROLES.admin, USER_ROLES.normal]
      },
      ncyBreadcrumb: {
        label: '订单管理'
      }
    })
    .state('orders.view', {
      url: '/:id',
      views: {
        '@': {
          templateUrl: 'tpls/order/edit.html',
          controller: 'OrderViewCtrl'
        }
      },
      ncyBreadcrumb: {
        label: '处理订单',
        parent: 'orders'
      },
      resolve: {
        Order: function($stateParams, OrderService){
          return OrderService.findOne({id: $stateParams.id}).$promise;
        }
      }
    })
    .state('orders.view.express', {
      url: '/express',
      views: {
        '@': {
          templateUrl: 'tpls/order/trackExpress.html',
          controller: 'OrderTrackExpressCtrl'
        }
      },
      ncyBreadcrumb: {
        label: '物流跟踪',
        parent: 'orders.view'
      },
      resolve: {
        Order: function($stateParams, OrderService){
          return OrderService.findOne({id: $stateParams.id}).$promise;
        }
      }
    })
    .state('orders.view.print', {
      url: '/print',
      views: {
        '@': {
          templateUrl: 'tpls/order/printOrderList.html',
          controller: 'OrderPrintCtrl'
        }
      },
      ncyBreadcrumb: {
        label: '打印商品清单',
        parent: 'orders.view'
      },
      resolve: {
        Order: function($stateParams, OrderService){
          return OrderService.findOne({id: $stateParams.id}).$promise;
        }
      }
    })
    .state('seckill', {
      url:'/seckill',
      templateUrl:'tpls/seckill/grid.html',
      controller:'SeckillListCtrl',
      data:{
        authorizedRoles:[USER_ROLES.admin, USER_ROLES.normal]
      },
      ncyBreadcrumb: {
        label: '秒杀管理'
      }
    })
    .state('seckill.add', {
      url:'/add',
      views:{
        '@':{
          templateUrl:'tpls/seckill/add.html',
          controller:'AddSeckillCtrl'
        }
      },
      ncyBreadcrumb: {
        label: '新增秒杀商品',
        parent: 'seckill'
      }
    })
    .state('seckill.edit', {
      url:'/:id/edit',
      views:{
        '@':{
          templateUrl:'tpls/seckill/edit.html',
          controller:'EditSeckillCtrl'
        }
      },
      ncyBreadcrumb: {
        label: '修改秒杀商品',
        parent: 'seckill'
      },
      resolve: {
        Seckill: function($stateParams, SeckillService){
          return SeckillService.findOne({id: $stateParams.id}).$promise;
        }
      }
    })
    .state('seckill.successkilled', {
      url:'/:id/successkilled',
      views:{
        '@':{
          templateUrl:'tpls/seckill/success-killed.html',
          controller:'SuccessKilledListCtrl'
        }
      },
      ncyBreadcrumb: {
        label: '秒杀成功列表',
        parent: 'seckill'
      }
    })
    .state('coupon', {
      url:'/coupon',
      templateUrl:'tpls/coupon/grid.html',
      controller:'CouponListCtrl',
      data:{
        authorizedRoles:[USER_ROLES.admin, USER_ROLES.normal]
      },
      ncyBreadcrumb: {
        label: '优惠券管理'
      }
    })
    .state('coupon.add', {
      url:'/add',
      views:{
        '@':{
          templateUrl:'tpls/coupon/add.html',
          controller:'AddCouponCtrl'
        }
      },
      ncyBreadcrumb: {
        label: '新增优惠券活动',
        parent: 'coupon'
      },
      resolve: {
        Unsaved: function(Store, BasicService){
          var unsaved = {};
          unsaved.id = Store.getUnsaved('coupon');

          BasicService.getUnsaved({}, { autoKey: unsaved.id }, function(data){
            unsaved.content = data.content;
          });
          return unsaved;
        }
      }
    })
    .state('coupon.edit', {
      url:'/:id/edit',
      views:{
        '@':{
          templateUrl:'tpls/coupon/edit.html',
          controller:'EditCouponCtrl'
        }
      },
      ncyBreadcrumb: {
        label: '修改优惠券活动',
        parent: 'coupon'
      },
      resolve: {
        Unsaved: function(Store, $stateParams, BasicService){
          var unsaved = {};
          unsaved.id = Store.getUnsaved('coupon', $stateParams.id);

          BasicService.getUnsaved({}, { autoKey: unsaved.id }, function(data){
            unsaved.content = data.content;
          });
          return unsaved;
        },
        Coupon: function($stateParams, CouponService){
          return CouponService.findOne({id: $stateParams.id}).$promise;
        }
      }
    })
    .state('coupon.view', {
      url:'/:id/detail',
      views:{
        '@':{
          templateUrl:'tpls/coupon/view.html',
          controller:'ViewCouponCtrl'
        }
      },
      ncyBreadcrumb: {
        label: '查看优惠券活动',
        parent: 'coupon'
      },
      resolve: {
        Coupon: function($stateParams, CouponService){
          return CouponService.findOne({id: $stateParams.id}).$promise;
        }
      }
    })
    .state('coupon.addgroup', {
      url:'/addgroup',
      views:{
        '@':{
          templateUrl:'tpls/coupon/addgroup.html',
          controller:'AddGroupCouponCtrl'
        }
      },
      ncyBreadcrumb: {
        label: '新增群组优惠券活动',
        parent: 'coupon'
      },
      resolve: {
        Unsaved: function(Store, BasicService){
          var unsaved = {};
          unsaved.id = Store.getUnsaved('coupon');

          BasicService.getUnsaved({}, { autoKey: unsaved.id }, function(data){
            unsaved.content = data.content;
          });
          return unsaved;
        }
      }
    })
    .state('coupon.addmember', {
      url:'/:id/addmember',
      views:{
        '@':{
          templateUrl:'tpls/coupon/addgroupmember.html',
          controller:'AddCouponGroupMemberCtrl'
        }
      },
      ncyBreadcrumb: {
        label: '新增群组成员',
        parent: 'coupon'
      },
      resolve: {
        Coupon: function($stateParams, CouponService){
          return CouponService.findOne({id: $stateParams.id}).$promise;
        }
      }
    })
    .state('groupbuy', {
      url:'/groupbuy',
      templateUrl:'tpls/groupbuy/grid.html',
      controller:'GroupBuyListCtrl',
      data:{
        authorizedRoles:[USER_ROLES.admin, USER_ROLES.normal]
      },
      ncyBreadcrumb: {
        label: '团购管理'
      }
    })
    .state('groupbuy.add', {
      url:'/add',
      views:{
        '@':{
          templateUrl:'tpls/groupbuy/add.html',
          controller:'AddGroupBuyCtrl'
        }
      },
      ncyBreadcrumb: {
        label: '新增团购商品',
        parent: 'groupbuy'
      },
      resolve: {
        Unsaved: function(Store, BasicService){
          var unsaved = {};
          unsaved.id = Store.getUnsaved('groupbuy');
          BasicService.getUnsaved({}, { autoKey: unsaved.id }, function(data){
            unsaved.content = data.content;
          });
          return unsaved;
        }
      }
    })
    .state('groupbuy.edit', {
      url:'/:id/edit',
      views:{
        '@':{
          templateUrl:'tpls/groupbuy/edit.html',
          controller:'EditGroupBuyCtrl'
        }
      },
      ncyBreadcrumb: {
        label: '修改团购商品',
        parent: 'groupbuy'
      },
      resolve: {
        Unsaved: function(Store, BasicService, $stateParams){
          var unsaved = {};
          unsaved.id = Store.getUnsaved('groupbuy', $stateParams.id);
          BasicService.getUnsaved({}, { autoKey: unsaved.id }, function(data){
            unsaved.content = data.content;
          });
          return unsaved;
        },
        Groupbuy: function($stateParams, GroupBuyService){
          return GroupBuyService.findOne({id: $stateParams.id}).$promise;
        }
      }
    })
    .state('auction', {
      url:'/auction',
      templateUrl:'tpls/auction/grid.html',
      controller:'AuctionListCtrl',
      data:{
        authorizedRoles:[USER_ROLES.admin, USER_ROLES.normal]
      },
      ncyBreadcrumb: {
        label: '拍卖管理'
      }
    })
    .state('auction.add', {
      url:'/add',
      views:{
        '@':{
          templateUrl:'tpls/auction/add.html',
          controller:'AddAuctionCtrl'
        }
      },
      ncyBreadcrumb: {
        label: '新增拍卖商品',
        parent: 'auction'
      },
      resolve: {
        Unsaved: function(Store, BasicService){
          var unsaved = {};
          unsaved.id = Store.getUnsaved('auction');
          BasicService.getUnsaved({}, { autoKey: unsaved.id }, function(data){
            unsaved.content = data.content;
          });
          return unsaved;
        }
      }
    })
    .state('auction.edit', {
      url:'/:id/edit',
      views:{
        '@':{
          templateUrl:'tpls/auction/edit.html',
          controller:'EditAuctionCtrl'
        }
      },
      ncyBreadcrumb: {
        label: '修改拍卖商品',
        parent: 'auction'
      },
      resolve: {
        Unsaved: function(Store, BasicService){
          var unsaved = {};
          unsaved.id = Store.getUnsaved('auction');
          BasicService.getUnsaved({}, { autoKey: unsaved.id }, function(data){
            unsaved.content = data.content;
          });
          return unsaved;
        },
        Auction: function($stateParams, AuctionService){
          return AuctionService.findOne({id: $stateParams.id}).$promise;
        }
      }
    })
    .state('auction.prices', {
      url:'/:id/prices',
      views:{
        '@':{
          templateUrl:'tpls/auction/pricelist.html',
          controller:'PriceListCtrl'
        }
      },
      ncyBreadcrumb: {
        label: '出价列表',
        parent: 'auction'
      },
      resolve: {
        Auction: function($stateParams, AuctionService){
          return AuctionService.findOne({id: $stateParams.id}).$promise;
        }
      }
    })
    .state('qrcode', {
      url:'/qrcode',
      templateUrl:'tpls/qrcode/index.html',
      controller:'QrcodeCtrl',
      data:{
        authorizedRoles:[USER_ROLES.admin, USER_ROLES.normal]
      },
      ncyBreadcrumb: {
        label: '生成产品二维码'
      }
    })
    .state('firstpay', {
      url:'/firstpay',
      templateUrl:'tpls/firstpay/grid.html',
      controller:'FirstpayListCtrl',
      data:{
        authorizedRoles:[USER_ROLES.admin, USER_ROLES.normal]
      },
      ncyBreadcrumb: {
        label: '首单特惠管理'
      }
    })
    .state('firstpay.add', {
      url:'/add',
      views:{
        '@':{
          templateUrl:'tpls/firstpay/add.html',
          controller:'AddFirstpayCtrl'
        }
      },
      ncyBreadcrumb: {
        label: '新增首单特惠商品',
        parent: 'firstpay'
      },
      resolve: {
        Unsaved: function(Store, BasicService){
          var unsaved = {};
          unsaved.id = Store.getUnsaved('firstpay');
          BasicService.getUnsaved({}, { autoKey: unsaved.id }, function(data){
            unsaved.content = data.content;
          });
          return unsaved;
        }
      }
    })
    .state('firstpay.edit', {
      url:'/:id/edit',
      views:{
        '@':{
          templateUrl:'tpls/firstpay/edit.html',
          controller:'EditFirstpayCtrl'
        }
      },
      ncyBreadcrumb: {
        label: '修改首单特惠商品',
        parent: 'firstpay'
      },
      resolve: {
        Unsaved: function(Store, BasicService, $stateParams){
          var unsaved = {};
          unsaved.id = Store.getUnsaved('firstpay', $stateParams.id);
          BasicService.getUnsaved({}, { autoKey: unsaved.id }, function(data){
            unsaved.content = data.content;
          });
          return unsaved;
        },
        Firstpay: function($stateParams, FirstpayService){
          return FirstpayService.findOne({id: $stateParams.id}).$promise;
        }
      }
    })
    .state('sharepay', {
      url:'/sharepay',
      templateUrl:'tpls/sharepay/grid.html',
      controller:'SharepayListCtrl',
      data:{
        authorizedRoles:[USER_ROLES.admin, USER_ROLES.normal]
      },
      ncyBreadcrumb: {
        label: '砍价管理'
      }
    })
    .state('sharepay.add', {
      url:'/add',
      views:{
        '@':{
          templateUrl:'tpls/sharepay/add.html',
          controller:'AddSharepayCtrl'
        }
      },
      ncyBreadcrumb: {
        label: '新增砍价商品',
        parent: 'sharepay'
      },
      resolve: {
        Unsaved: function(Store, BasicService){
          var unsaved = {};
          unsaved.id = Store.getUnsaved('sharepay');
          BasicService.getUnsaved({}, { autoKey: unsaved.id }, function(data){
            unsaved.content = data.content;
          });
          return unsaved;
        }
      }
    })
    .state('sharepay.edit', {
      url:'/:id/edit',
      views:{
        '@':{
          templateUrl:'tpls/sharepay/edit.html',
          controller:'EditSharepayCtrl'
        }
      },
      ncyBreadcrumb: {
        label: '修改砍价商品',
        parent: 'sharepay'
      },
      resolve: {
        Unsaved: function(Store, BasicService, $stateParams){
          var unsaved = {};
          unsaved.id = Store.getUnsaved('sharepay', $stateParams.id);
          BasicService.getUnsaved({}, { autoKey: unsaved.id }, function(data){
            unsaved.content = data.content;
          });
          return unsaved;
        },
        Sharepay: function($stateParams, FirstpayService){
          return FirstpayService.findOne({id: $stateParams.id}).$promise;
        }
      }
    })
    .state('tuan', {
      url:'/tuan',
      templateUrl:'tpls/tuan/grid.html',
      controller:'TuanListCtrl',
      data:{
        authorizedRoles:[USER_ROLES.admin, USER_ROLES.normal]
      },
      ncyBreadcrumb: {
        label: '拼团管理'
      }
    })
    .state('tuan.add', {
      url:'/add',
      views:{
        '@':{
          templateUrl:'tpls/tuan/add.html',
          controller:'AddTuanCtrl'
        }
      },
      ncyBreadcrumb: {
        label: '新增拼团',
        parent: 'tuan'
      },
      resolve: {
        Unsaved: function(Store, BasicService){
          var unsaved = {};
          unsaved.id = Store.getUnsaved('tuan');
          BasicService.getUnsaved({}, { autoKey: unsaved.id }, function(data){
            unsaved.content = data.content;
          });
          return unsaved;
        }
      }
    })
    .state('tuan.edit', {
      url:'/:id/edit',
      views:{
        '@':{
          templateUrl:'tpls/tuan/edit.html',
          controller:'EditTuanCtrl'
        }
      },
      ncyBreadcrumb: {
        label: '修改拼团',
        parent: 'tuan'
      },
      resolve: {
        Unsaved: function(Store, BasicService, $stateParams){
          var unsaved = {};
          unsaved.id = Store.getUnsaved('tuan', $stateParams.id);
          BasicService.getUnsaved({}, { autoKey: unsaved.id }, function(data){
            unsaved.content = data.content;
          });
          return unsaved;
        },
        Tuan: function($stateParams, FirstpayService){
          return FirstpayService.findOne({id: $stateParams.id}).$promise;
        }
      }
    })
    .state('channel', {
      url:'/channel',
      views:{
        '@':{
          templateUrl:'tpls/channel/grid.html',
          controller:'ChannelListCtrl'
        }
      },
      data:{
        authorizedRoles:[USER_ROLES.admin, USER_ROLES.normal]
      },
      ncyBreadcrumb: {
        label: '栏目管理'
      }
    })
    .state('channel.add', {
      url:'/add',
      views:{
        '@':{
          templateUrl:'tpls/channel/add.html',
          controller:'AddChannelCtrl'
        }
      },
      ncyBreadcrumb: {
        label: '新增栏目',
        parent: 'channel'
      }
    })
    .state('channel.edit', {
      url:'/edit/:id',
      views:{
        '@':{
          templateUrl:'tpls/channel/edit.html',
          controller:'EditChannelCtrl'
        }
      },
      ncyBreadcrumb: {
        label: '更新栏目',
        parent: 'channel'
      },
      resolve:{
        Channel: function(ChannelService, $stateParams){
          return ChannelService.findOne({id: $stateParams.id}).$promise;
        }
      }
    })
    .state('channel.goods', {
      url:'/:id/goods',
      views:{
        '@':{
          templateUrl:'tpls/channel/goods/grid.html',
          controller:'ChannelGoodsListCtrl'
        }
      },
      ncyBreadcrumb: {
        label: '栏目商品管理',
        parent: 'channel'
      },
      resolve:{
        Cid:function($stateParams){
          return $stateParams.id;
        }
      }
    })
    .state('channel.goods.add', {
      url:'/add',
      views:{
        '@':{
          templateUrl:'tpls/channel/goods/add.html',
          controller:'AddChannelGoodsCtrl'
        }
      },
      ncyBreadcrumb: {
        label: '新增栏目商品',
        parent: 'channel.goods'
      }
    })
    .state('inventory', {
      url:'/inventory',
      views:{
        '@':{
          templateUrl:'tpls/inventory/grid.html',
          controller:'InventoryListCtrl'
        }
      },
      data:{
        authorizedRoles:[USER_ROLES.admin, USER_ROLES.normal]
      },
      ncyBreadcrumb: {
        label: '库存商品管理'
      }
    })
    .state('inventory.add', {
      url:'/add',
      views:{
        '@':{
          templateUrl:'tpls/inventory/add.html',
          controller:'AddInventoryCtrl'
        }
      },
      ncyBreadcrumb: {
        label: '新增库存商品',
        parent: 'inventory'
      }
    })
    .state('inventory.edit', {
      url:'/edit/:id',
      views:{
        '@':{
          templateUrl:'tpls/inventory/edit.html',
          controller:'EditInventoryCtrl'
        }
      },
      ncyBreadcrumb: {
        label: '更新库存商品',
        parent: 'inventory'
      }
    });
  })

  /**
   * 国际化配置
   */
  .config(function($translateProvider, $sceDelegateProvider){
    $translateProvider.storageKey('lang');
    $translateProvider.useCookieStorage();

    //动态加载
    //$translateProvider.useUrlLoader('/api/lang');

    //静态加载
    /* 
    $translateProvider
      .translations('en', {
        LANG:'Language: English'
      })
      .translations('zh', {
        LANG:'当前语种：中文'
      });
    */
    $translateProvider.preferredLanguage('en');

    $sceDelegateProvider.resourceUrlWhitelist([
       // Allow same origin resource loads.
       'self',
       // Allow loading from our assets domain.  Notice the difference between * and **.
       'http://pe1975mall.yihuyixi.com/**', 'about:blank']);
  })

  /**
   * 应用控制器
   */
  .controller('AppController', function ($scope, $state, USER_ROLES, AuthService, Session, $rootScope, TagService, $interval, UserService, AUTH_EVENTS, Config, BasicService, Store){
    $scope.userRoles = USER_ROLES;
    // $scope.isAuthorized = AuthService.isAuthorized();

    $scope.setCurrentUser = function (user) {
      $scope.currentUser = user;
      loadUserPriviledges(user && user.userId);
      $scope.$emit("updateTag");
    };

    var watcher = $scope.$watch('currentUser', function(nextVal, oldVal){
      if(nextVal){
        watcher();
        loadUserPriviledges(Session.user && Session.user.userId);
      }
    });
    
    $scope.logOff = function(){
      AuthService.logOff($scope.currentUser.userId).then(function(update){
        $scope.currentUser = null;
        $rootScope.userPriviledges = [];
        $state.go('login');
      });
    };

    $scope.$on("updateTag", function(event, data){
      var userName = $scope.currentUser && $scope.currentUser.userName;
      if(!userName){
        return;
      }
      TagService.getList({userName:userName}, function(data){
        var items = data || [];
        var tags = [];
        for(var i=0, len=items.length; i<len; i++){
          tags.push({id: items[i].id, text: items[i].name, weight: items[i].weight || 1});
        }
        $rootScope.tags = tags; 
      });
    });
    $scope.$emit("updateTag");

    ssoTimerId = $interval(refreshSSO, Config.ssoInterval); 
    refreshSSO();

    function refreshSSO(){
      var userId = $scope.currentUser && $scope.currentUser.userId;
      if(!userId){
        relogin();
        return;
      }

      UserService.refreshSSO({userId: userId}, function(data){
        if(data && (data.result==1)){
          relogin();
          return;
        }
        Store.setExpires("user", Config.autoLoginDuration || (24*3600000));
      }, function(err){
        console.log('refreshSSO encounted error, status=' + err.status + ', message=' + err.statusText);
        relogin();
        return;
      });
    } 

    function relogin(){
      $scope.currentUser = null;
      var currentName = $state.current.name;
      if(currentName == 'login'){
        $rootScope.$broadcast(AUTH_EVENTS.sessionTimeout);
      }else{
        $rootScope.$broadcast(AUTH_EVENTS.sessionTimeout, {from: $state.current.name, params: $state.params && $state.params.id});
      }
    }

    $scope.$on('$destroy', function(){
      $interval.cancel(timerId);
      $rootScope.userPriviledges = [];
    });

    function loadUserPriviledges(userId){
      if(userId){
        UserService.getUserPriviledge({userId: userId}, function(data){
          var permissions = data && data.info || [];
          $rootScope.userPriviledges = permissions;

          BasicService.getNav(function(json){
            for(var index=0; index<json.length; index++){
              var item = json[index];
              var flag = true;
              var savedChildsIdx = [];
              permissions.forEach(p => {
                if (p.operationType == 1 && item.label == p.permitName) {
                  flag = false;
                } else if (p.operationType == 2 && item.children) {
                  for (var j=0; j<item.children.length; j++) {
                    var subNode = item.children[j];
                    if (subNode.label == p.permitName) {
                      savedChildsIdx.push(j);
                    }
                  }
                } else if(item.label == '首页') {
                  flag = false;
                }
              });
              if (flag) {
                json.splice(index, 1);
                index--;
              }
              if (savedChildsIdx.length) {
                for (var k=item.children.length; k>=0; k--) {
                  if (savedChildsIdx.indexOf(k) == -1) {
                    item.children.splice(k, 1);
                  }
                }
              }
            }
            $rootScope.navbar = json;            
          });
        });
      }
    }

    // setTimeout(function(){
    //   if(!$rootScope.navbar || $rootScope.navbar.length===0){
    //     BasicService.getNav(function(json){
    //       $rootScope.navbar = json;
    //       console.log(json);
    //     });
    //   }
    // }, 1000);

    $scope.showMenu = function(item){
      if(!Config.enableAuth){
        return true;
      }
      var userPriviledges = $rootScope.userPriviledges;
      if(item && item.link && userPriviledges){
        var links = item.link.split('.');
        for(var i=0; i<userPriviledges.length; i++){
          var priviledge = userPriviledges[i];
          if(Config.authType.navMenu === priviledge.resourceType && priviledge.resourceURI.indexOf(item.link) >= 0){
            return true;
          }else if(Config.authType.navMenu === priviledge.resourceType && item.link.indexOf('.')>=0){
            for(var j=0; j<links.length; j++){
              if(priviledge.resourceURI.indexOf(links[j]) < 0){
                return false; 
              }
            }
            return true;
          }
        }
        return false;
      }
      return true;
    };
  })

  /**
   * 变更当前国际化语种
   */
  .controller('LocaleController', function($translate, $rootScope){
    $rootScope.langKey = $translate.preferredLanguage();

    $scope.changeLanguage = function(langKey){
      $translate.use(langKey);    
      $rootScope.langKey = langKey;
    };
  })
  .controller('StatsController', function($rootScope, InventoryService){
    InventoryService.stat(function(data) {
      if (data.result == 0) {
        $rootScope.InventoryStats = data.data;
        if ($rootScope.InventoryStats.markPriceTotal) {
          $rootScope.InventoryStats.marketTotal = parseFloat($rootScope.InventoryStats.markPriceTotal).toLocaleString();
        } else {
          $rootScope.InventoryStats.marketTotal = 0;
        }
        if ($rootScope.InventoryStats.buyPriceTotal) {
          $rootScope.InventoryStats.costTotal = parseFloat($rootScope.InventoryStats.buyPriceTotal).toLocaleString();
        } else {
          $rootScope.InventoryStats.costTotal = 0;
        }
      }
    });
  })

  //产品库
  .controller('ProductLibCtrl', function(ArtworkService, $scope, $rootScope){
    $scope.productLibPager = {
      pageNumber: 1,
      pageSize: 20
    };
    $scope.productLibSearch = {};
    $rootScope.choosedProduct = {};
    $rootScope.multiSelectProducts = [];

    $scope.getPage = function(){
      var params = {
        currentPage:$scope.productLibPager.pageNumber, 
        pageSize:$scope.productLibPager.pageSize,
        name: $scope.productLibSearch.name || '',
        artworkTypeName: "tea"
      };
      ArtworkService.getList(params, function(data){
        $scope.artworkLibs = data;
      });
    };

    $scope.goodsSearch = function() {
      $scope.productLibPager.pageNumber = 1;
      $scope.getPage();
    }

    $scope.prevPage = function(){
      $scope.productLibPager.pageNumber--;
      $scope.getPage();
    };

    $scope.nextPage = function(){
      $scope.productLibPager.pageNumber++;
      $scope.getPage();
    };

    $scope.chooseProduct = function(product){
      $rootScope.choosedProduct = product;
    };

    $scope.multiSelect = function(product) {
      var flag = false;
      $rootScope.multiSelectProducts.forEach(function(value, key){
        if (product.id === value.id) {
          $rootScope.multiSelectProducts.splice(key, 1);
          flag = true;
        }
      });
      if (!flag) {
        $rootScope.multiSelectProducts.push(product);
      }
    };

    $scope.containProduct = function(product) {
      var products = $rootScope.multiSelectProducts;
      var flag = false;
      if (products.length) {
        products.forEach(function(item) {
          if (item.id === product.id) {
            flag = true;
          }
        });
      }
      return flag;
    };

    $scope.ok = function() {
      var selected = [];
      $rootScope.multiSelectProducts.forEach(function(item) {
        selected.push(item);
      });
      if($rootScope.selectedProducts && $rootScope.selectedProducts.length) {
        selected.forEach(function(item) {
          var flag = false;
          $rootScope.selectedProducts.forEach(function(o) {
            if (o.id === item.id) {
              flag = true;
            }
          });
          if (!flag) {
            $rootScope.selectedProducts.push(item);
          }
        });
      } else if (selected.length) {
        $rootScope.selectedProducts = selected;
      }
    };

    $scope.discard = function(){
      $rootScope.choosedProduct = {};
      $rootScope.multiSelectProducts = [];
    };

    $scope.getPage();
  })
  .controller('BargainLibCtrl', function(FirstpayService, $scope, $rootScope){
    $scope.productLibPager = {
      pageNumber: 1,
      pageSize: 20
    };
    $scope.productLibSearch = {};
    $rootScope.selectedBargainGood = {};
    $rootScope.multiSelectBarginGoods = [];

    $scope.getPage = function(){
      var params = {
        currentPage:$scope.productLibPager.pageNumber, 
        pageSize:$scope.productLibPager.pageSize,
        name: $scope.productLibSearch.name || '',
        type: 1
      };
      FirstpayService.getList(params, function(data){
        $scope.barginGoods = data;
      });
    };

    $scope.goodsSearch = function() {
      $scope.productLibPager.pageNumber = 1;
      $scope.getPage();
    }

    $scope.prevPage = function(){
      $scope.productLibPager.pageNumber--;
      $scope.getPage();
    };

    $scope.nextPage = function(){
      $scope.productLibPager.pageNumber++;
      $scope.getPage();
    };

    $scope.chooseProduct = function(product){
      $rootScope.selectedBargainGood = product;
    };

    $scope.multiSelectBargain = function(product) {
      var flag = false;
      $rootScope.multiSelectBarginGoods.forEach(function(value, key){
        if (product.id === value.id) {
          $rootScope.multiSelectBarginGoods.splice(key, 1);
          flag = true;
        }
      });
      if (!flag) {
        $rootScope.multiSelectBarginGoods.push(product);
      }
    };

    $scope.containBargain = function(product) {
      var products = $rootScope.multiSelectBarginGoods;
      var flag = false;
      if (products.length) {
        products.forEach(function(item) {
          if (item.id == product.id) {
            flag = true;
          }
        });
      }
      return flag;
    };

    $scope.bargainDone = function() {
      var selected = [];
      $rootScope.multiSelectBarginGoods.forEach(function(item) {
        selected.push(item);
      });
      if($rootScope.selectedBargainGoods && $rootScope.selectedBargainGoods.length) {
        selected.forEach(function(item) {
          var flag = false;
          $rootScope.selectedBargainGoods.forEach(function(o) {
            if (o.id === item.id) {
              flag = true;
            }
          });
          if (!flag) {
            $rootScope.selectedBargainGoods.push(item);
          }
        });
      } else if (selected.length) {
        $rootScope.selectedBargainGoods = selected;
      }
    };

    $scope.cancelBargain = function(){
      $rootScope.selectedBargainGood = {};
      $rootScope.multiSelectBarginGoods = [];
    };

    $scope.getPage();
  })


  /** 
   * 三级导航组件
   */
  .controller('NavbarCtrl', function ($scope){  
    $scope.logo = {
      "text":"小茶馆", 
      "link":"index"
    };

    $scope.topbar = {
      title:"菜单",
      messages:{
        list: [{
          link:"message",
          text:"您有6条未读消息",
          icon:"fa fa-envelope",
          time:"1分钟前",
          count:6
        },{
          link:"message",
          text:"2条新回复",
          icon:"fa fa-qq",
          time:"1天前",
          count:2
        }],
        more:{
          link:"message",
          text:"查看所有",
          icon:"fa fa-ellipsis-h"
        },
        total:8
      },
      setting:[{
        link:"setting",
        text:"系统设置",
        icon:"fa fa-gear"
      },{
        link:"message",
        text:"我的消息",
        icon:"fa fa-comments-o"
      },{
        link:"follow",
        text:"我的关注",
        icon:"fa fa-heart-o"
      },{
        link:"stats",
        text:"用户统计",
        icon:"fa fa-line-chart"
      }],
      user:[{
        link:"user.changePwd",
        text:"修改密码",
        icon:"fa fa-edit"
      },{
        trigger:'logOff',
        text:"退出登录",
        icon:"fa fa-power-off"
      }]
    };
  })

  .filter('trustHtml', function ($sce) {
    return function (input) {
      return $sce.trustAsHtml(input);
    };
  })
  .filter('mobileFilter', function(){
    return function(input){
      if(!input){
        return '';
      }

      if(input.length === 11){
        var prefix = input.substring(0, 3);
        var suffix = input.substring(7);
        return prefix+'****'+suffix;
      }
      return input;
    };
  });

})();